import React, { useState, useEffect } from 'react'
import { Card, Button, Form, Input, Select, Tree, Transfer, Modal, Table, message } from 'antd'
import axios from '../../axios/index'
import menuConfig from '../../config/menuConfig'
import Utils from '../../utils/utils'

const Option = Select.Option;
const TreeNode = Tree.TreeNode;

const Permission = () => {
  const [selectedItem, setSelectedItem] = useState(null)
  const [list, setList] = useState([])
  const [isRoleVisible, setisRoleVisible] = useState(false)
  const [isPermVisible, setIsPermVisible] = useState(false)
  const [isRoleAuthVisible, setIsRoleAuthVisible] = useState(false)
  const [detailInfo, setDetailInfo] = useState(null)
  const [menuInfo, setMenuInfo] = useState(null)
  const [targetKeys, setTargetKeys] = useState([])
  const [mockData, setMockData] = useState([])

  const onRoleCreate = (values) => {
    setisRoleVisible(false)
    axios.ajax({
      url: '/role/create',
      data: {
        params: {
          ...values
        }
      }
    }).then((res) => {
      if (res.status === 200 && res.code === 0) {
        message.success(res.result)
        setisRoleVisible(false)
        requestList()
      }
    })
  }

  const onPermVisibleCreate = (values) => {
    let data = {}
    data.menus = menuInfo
    data.role_id = detailInfo[0]._id
    console.log('提交数据', data)
    axios.ajax({
      url: '/role/permission',
      data: {
        params: {
          ...data
        }
      }
    }).then((res) => {
      if (res.status === 200 && res.code === 0) {
        message.success(res.result)
        setIsPermVisible(false)
        requestList()
      }
    })
  }

  const onRoleAuthCreate = (values) => {
    console.log('onRoleAuthCreate', values)
  }

  const requestList = () => {
    axios.ajax({
      url: '/role/list',
      data: {
        params: {}
      }
    }).then((res) => {
      if (res.code === 0) {
        let list = res.result.item_list.map((item, i) => {
          item.key = i;
          return item;
        })
        setList(list)
      }
    })
  }

  useEffect(() => {
    requestList()
  }, [])

  // 角色创建
  const handleRole = () => {
    setisRoleVisible(true)
  }

  // 权限设置
  const handlePermission = () => {
    if (!selectedItem) {
      Modal.info({
        title: '信息',
        content: '请选择一个角色'
      })
      return;
    }
    setIsPermVisible(true)
    setDetailInfo(selectedItem)
    let menuList = selectedItem[0].menus
    setMenuInfo(menuList)
  }

  // 用户授权
  const handleUserAuth = () => {
    if (!selectedItem) {
      Modal.info({
        title: '信息',
        content: '请选择一个角色'
      })
      return;
    }
    setIsRoleAuthVisible(true)
    setDetailInfo(selectedItem)
    getRoleUserList(selectedItem[0].role_name)
  }

  const getRoleUserList = (id) => {
    axios.ajax({
      url: '/role/user_list',
      data: {
        params: {
          id: id
        }
      }
    }).then((res) => {
      if (res) {
        getAuthUserList(res.result.item_list);
      }
    })
  }
  // 筛选目标用户
  const getAuthUserList = (dataSource) => {
    const mockData = [];
    const targetKeys = [];
    if (dataSource && dataSource.length > 0) {
      for (let i = 0; i < dataSource.length; i++) {
        const data = {
          key: dataSource[i].user_id,
          title: dataSource[i].user_name,
          status: dataSource[i].status,
        };
        if (data.status === 1) {
          targetKeys.push(data.key);
        } else {
          mockData.push(data);
        }
      }
    }
    setTargetKeys(targetKeys)
    setMockData(mockData)
  }

  const columns = [
    {
      title: '角色ID',
      dataIndex: 'id'
    }, {
      title: '角色名称',
      dataIndex: 'role_name'
    }, {
      title: '创建时间',
      dataIndex: 'create_time',
      render: Utils.formateDate
    }, {
      title: '使用状态',
      dataIndex: 'status',
      render(status) {
        if (status === 1) {
          return "启用"
        } else {
          return "停用"
        }
      }
    }, {
      title: '授权时间',
      dataIndex: 'authorize_time',
      render: Utils.formateDate
    }, {
      title: '授权人',
      dataIndex: 'authorize_user_name',
    }
  ]

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('选择信息', selectedRows);
      setSelectedItem(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  return (
    <div style={{ width: '100%' }}>
      <Card style={{ paddingTop: 10 }}>
        <Button type="primary" onClick={handleRole}>创建角色</Button>
        <Button type="primary" onClick={handlePermission}>设置权限</Button>
        <Button type="primary" onClick={handleUserAuth}>用户授权</Button>
      </Card>
      <div className="content-wrap">
        <Table
          columns={columns}
          rowSelection={{
            type: 'radio',
            ...rowSelection,
          }}
          dataSource={list}
        />
      </div>
      <RoleForm
        visible={isRoleVisible}
        onCreate={onRoleCreate}
        onCancel={() => {
          setisRoleVisible(false);
        }}
      />
      <PermEditForm
        visible={isPermVisible}
        onCreate={onPermVisibleCreate}
        onCancel={() => {
          setIsPermVisible(false);
        }}
        detailInfo={detailInfo}
        menuInfo={menuInfo}
        setMenuInfo={setMenuInfo}
      />
      <RoleAuthForm
        visible={isRoleAuthVisible}
        onCreate={onRoleAuthCreate}
        onCancel={() => {
          setIsRoleAuthVisible(false);
        }}
        detailInfo={detailInfo}
        targetKeys={targetKeys}
        setTargetKeys={setTargetKeys}
        mockData={mockData}
      />
    </div>
  )
}

const RoleForm = ({ visible, onCreate, onCancel }) => {
  const [form] = Form.useForm()

  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 16 }
  }
  return (
    <div>
      <Modal
        visible={visible}
        title="创建角色"
        okText="确认"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="horizontal"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item name="role_name" label="角色名称" {...formItemLayout}>
            <Input type="text" placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item name="id" label="角色ID" {...formItemLayout}>
            <Input type="text" placeholder="请输入角色ID" />
          </Form.Item>
          <Form.Item name="status" label="状态" {...formItemLayout}>
            <Select>
              <Option value={1}>开启</Option>
              <Option value={0}>关闭</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

const PermEditForm = ({ visible, onCreate, onCancel, detailInfo, menuInfo, setMenuInfo }) => {
  const [form] = Form.useForm()
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
  }

  // console.log('menuInfo', menuInfo)

  const onCheck = (checkedKeys) => {
    // console.log('checkedKeys', checkedKeys)
    setMenuInfo(checkedKeys)
  }

  // 渲染所有的菜单
  const renderTreeNodes = (data, key = '') => {
    // console.log('data', data)
    return data.map((item) => {
      let parentKey = key + item.key;
      if (item.children) {
        return (
          <TreeNode title={item.title} key={parentKey} dataRef={item} className="op-role-tree">
            {renderTreeNodes(item.children, parentKey)}
          </TreeNode>
        );
      } else if (item.btnList) {
        return (
          <TreeNode title={item.title} key={parentKey} dataRef={item} className="op-role-tree">
            { renderBtnTreedNode(item, parentKey)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  };

  const renderBtnTreedNode = (menu, parentKey = '') => {
    const btnTreeNode = []
    menu.btnList.forEach((item) => {
      // console.log(parentKey + '-btn-' + item.key);
      btnTreeNode.push(<TreeNode title={item.title} key={parentKey + '-btn-' + item.key} className="op-role-tree" />);
    })
    return btnTreeNode;
  }

  return (
    <div>
      <Modal
        visible={visible}
        title="设置权限"
        okText="确认"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}>
        <Form
          form={form}
          layout="horizontal"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item name="角色名称" label="角色名称" {...formItemLayout}>
            {
              detailInfo && detailInfo[0].role_name ? <Input disabled maxLength="8" placeholder={detailInfo[0].role_name} /> : ''
            }
          </Form.Item>
          <Form.Item name="状态" label="状态" {...formItemLayout}>
            <Select placeholder="启用" style={{ width: 80 }}>
              <Option value="1">启用</Option>
              <Option value="0">停用</Option>
            </Select>
          </Form.Item>
          <Tree
            checkable
            defaultExpandAll
            onCheck={(checkedKeys) => onCheck(checkedKeys)}
            checkedKeys={menuInfo || []}
          >
            <TreeNode title="平台权限" key="platform_all">
              {renderTreeNodes(menuConfig)}
            </TreeNode>
          </Tree>
        </Form>
      </Modal>
    </div>
  )
}

const RoleAuthForm = ({ visible, onCreate, onCancel, detailInfo, targetKeys, mockData, setTargetKeys }) => {
  const [form] = Form.useForm()
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
  }

  const onChange = (nextTargetKeys, direction, moveKeys) => {
    console.log('targetKeys:', nextTargetKeys);
    console.log('direction:', direction);
    console.log('moveKeys:', moveKeys);
    setTargetKeys(nextTargetKeys);
  };

  return (
    <div>
      <Modal
        visible={visible}
        title="用户授权"
        okText="确认"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}>
        <Form
          form={form}
          layout="horizontal"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item name="角色名称" label="角色名称" {...formItemLayout}>
            {
              detailInfo && detailInfo[0].role_name ? <Input disabled maxLength="8" placeholder={detailInfo[0].role_name} /> : ''
            }
          </Form.Item>
          <Form.Item name="选择用户：" label="状态" {...formItemLayout}>
            <Transfer
              listStyle={{ width: 200, height: 400 }}
              dataSource={mockData}
              showSearch
              titles={['待选用户', '已选用户']}
              searchPlaceholder='输入用户名'
              targetKeys={targetKeys}
              onChange={onChange}
              render={item => item.title}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Permission